import { MigrationInterface, QueryRunner } from 'typeorm';
import * as bcrypt from 'bcrypt';

export class FixEmptyPasswords1625000000003 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    console.log('开始修复空密码问题...');

    // 检查表是否存在
    const tableExists = await queryRunner.hasTable('users');
    if (!tableExists) {
      console.log('users 表不存在，跳过此迁移');
      return;
    }

    // 获取所有密码为空的用户
    const users = await queryRunner.query(
      `SELECT id, username FROM users WHERE password IS NULL OR password = ''`
    );

    if (users.length === 0) {
      console.log('没有找到密码为空的用户');
      return;
    }

    console.log(`找到 ${users.length} 个密码为空的用户`);

    // 生成默认密码的哈希值 (默认密码: '123456')
    const salt = await bcrypt.genSalt();
    const defaultPasswordHash = await bcrypt.hash('123456', salt);

    // 更新所有空密码的用户
    await queryRunner.query(
      `UPDATE users SET password = ? WHERE password IS NULL OR password = ''`,
      [defaultPasswordHash]
    );

    console.log('已将所有空密码用户的密码重置为默认密码');
    console.log('默认密码为: 123456');
    console.log('请提醒这些用户尽快修改密码');

    // 记录修复的用户ID
    console.log('已修复的用户ID:');
    users.forEach((user: any) => {
      console.log(`ID: ${user.id}, 用户名: ${user.username || '未设置'}`);
    });
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    console.log('此迁移不支持回滚');
  }
}

